<?php


namespace app\community\oauth2\Entities;


use app\community\oauth2\Exception\ClientException;
use app\community\oauth2\Exception\ClientNotFoundException;
use app\community\oauth2\Model\oauthClientModel;
use iflow\Container\implement\annotation\tools\data\Inject;
use League\OAuth2\Server\Entities\ClientEntityInterface;

class ClientEntity implements ClientEntityInterface {

    #[Inject]
    public oauthClientModel $oauthClientModel;

    protected array $clientUserInfo = [];

    public function __construct(protected string $clientId, protected string $clientSecret = '') {}

    public function getClient(): static
    {
        $this->clientUserInfo = $this->oauthClientModel -> getClientById($this->clientId);
        if (!$this->clientUserInfo) {
            throw new ClientNotFoundException('Account does not exist or clientId error', 403);
        }
        return $this;
    }

    public function getIdentifier(): string
    {
        // TODO: Implement getIdentifier() method.
        return $this->clientId;
    }

    public function getName(): string
    {
        // TODO: Implement getName() method.
        return $this->clientUserInfo['app_name'];
    }

    public function getRedirectUri(): string
    {
        // TODO: Implement getRedirectUri() method.
        if ($this->clientUserInfo['redirect_uri'] !== request() -> params('redirect_uri')) {
            throw new ClientException('redirect_uri verification failed');
        }
        return $this->clientUserInfo['redirect_uri'];
    }

    public function isConfidential(): bool
    {
        // TODO: Implement isConfidential() method.
        return true;
    }

    public function getClientSecret()
    {
        return $this->clientUserInfo['app_secret'];
    }

    /**
     * 验证客户端 密钥
     * @param string $clientSecret
     * @return bool
     */
    public function validateClient(string $clientSecret): bool
    {
        if (!$this->clientUserInfo) return false;
        return $clientSecret === $this->getClientSecret();
    }
}